<template>
    <div class="orderInfo">
        <!-- 标题栏 -->
        <div class="header">
            <span class="title">创建订单</span>
            <van-button plain hairline class="back-btn" @click="$router.go(-1)">
                <van-icon class="list-icon" name="revoke" />
            </van-button>
        </div>

        <!-- 订单信息表单 -->
        <div class="form-container">
            <!-- 停车点位选择 -->
            <div class="form-item">
                <label>停车点位选择：</label>
                <van-field v-model="selectedParkingText" readonly clickable placeholder="请选择停车点位"
                    @click="showParkingPicker = true" right-icon="arrow-down" />
                <van-popup v-model:show="showParkingPicker" position="bottom">
                    <van-picker show-toolbar :columns="parkingOptions" @confirm="onParkingConfirm"
                        @cancel="showParkingPicker = false" />
                </van-popup>
            </div>

            <!-- 泊位选择 -->
            <div class="form-item">
                <label>泊位选择：</label>
                <van-field v-model="selectedBerthText" readonly clickable placeholder="请选择泊位" @click="onBerthClick"
                    :disabled="!selectedParking" right-icon="arrow-down" />
                <van-popup v-model:show="showBerthPicker" position="bottom">
                    <van-picker show-toolbar :columns="berthOptions" @confirm="onBerthConfirm"
                        @cancel="showBerthPicker = false" />
                </van-popup>
            </div>

            <!-- 车牌号码 -->
            <div class="form-item">
                <label>车牌号码：</label>
                <van-field v-model="licensePlate" placeholder="请输入车牌信息" />
            </div>

            <!-- VIM码 -->
            <div class="form-item">
                <label>车辆VIM码：</label>
                <van-field v-model="vimCode" placeholder="无牌车请输入VIM码" />
            </div>

            <!-- 入场时间 -->
            <div class="form-item">
                <label>入场时间：</label>
                <div class="time-picker">
                    <van-field v-model="year" readonly clickable @click="showYearPicker = true"
                        right-icon="arrow-down" />
                    年
                    <van-popup v-model:show="showYearPicker" position="bottom">
                        <van-picker show-toolbar :columns="yearOptions" @confirm="onYearConfirm"
                            @cancel="showYearPicker = false" />
                    </van-popup>
                    <van-field v-model="month" readonly clickable @click="showMonthPicker = true"
                        right-icon="arrow-down" />
                    月
                    <van-popup v-model:show="showMonthPicker" position="bottom">
                        <van-picker show-toolbar :columns="monthOptions" @confirm="onMonthConfirm"
                            @cancel="showMonthPicker = false" />
                    </van-popup>
                    <van-field v-model="day" readonly clickable @click="showDayPicker = true" right-icon="arrow-down" />
                    日
                    <van-popup v-model:show="showDayPicker" position="bottom">
                        <van-picker show-toolbar :columns="dayOptions" @confirm="onDayConfirm"
                            @cancel="showDayPicker = false" />
                    </van-popup>
                </div>
                <div class="time-picker">
                    <van-field v-model="hour" readonly clickable @click="showHourPicker = true"
                        right-icon="arrow-down" />
                    时
                    <van-popup v-model:show="showHourPicker" position="bottom">
                        <van-picker show-toolbar :columns="hourOptions" @confirm="onHourConfirm"
                            @cancel="showHourPicker = false" />
                    </van-popup>
                    <van-field v-model="minute" readonly clickable @click="showMinutePicker = true"
                        right-icon="arrow-down" />
                    分
                    <van-popup v-model:show="showMinutePicker" position="bottom">
                        <van-picker show-toolbar :columns="minuteOptions" @confirm="onMinuteConfirm"
                            @cancel="showMinutePicker = false" />
                    </van-popup>
                    <van-field v-model="second" readonly clickable @click="showSecondPicker = true"
                        right-icon="arrow-down" />
                    秒
                    <van-popup v-model:show="showSecondPicker" position="bottom">
                        <van-picker show-toolbar :columns="secondOptions" @confirm="onSecondConfirm"
                            @cancel="showSecondPicker = false" />
                    </van-popup>
                </div>
            </div>

            <!-- 创建订单按钮 -->
            <div class="form-item">
                <van-button :color="isFormValid ? 'rgb(47,111,226)' : '#aaa'" :disabled="!isFormValid" block
                    @click="createOrder">
                    <span :style="{
              color: isFormValid ? 'white' : '#666',
              fontWeight: 'bold'
            }">
                        创建订单
                    </span>
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        parkData: {
            type: Object,
            default: () => {}
        },
        parkData1: {
            type: Object,
            default: () => ({
                parking_spot: '',
                berth: ''
            })
        }
    },
    data() {
        const now = new Date();
        return {
            selectedParking: "", // 选中的停车点位值
            selectedParkingText: "", // 选中的停车点位显示文本
            selectedBerth: "", // 选中的泊位值
            selectedBerthText: "", // 选中的泊位显示文本
            licensePlate: "",
            vimCode: "",
            year: now.getFullYear(),
            month: now.getMonth() + 1,
            day: now.getDate(),
            hour: now.getHours(),
            minute: now.getMinutes(),
            second: now.getSeconds(),
            showParkingPicker: false, // 控制停车点位选择器的显示
            showBerthPicker: false, // 控制泊位选择器的显示
            showYearPicker: false,
            showMonthPicker: false,
            showDayPicker: false,
            showHourPicker: false,
            showMinutePicker: false,
            showSecondPicker: false,
            parkingOptions: [
                {
                    text: "A1路侧停车点",
                    value: "A1"
                },
                {
                    text: "B2路侧停车点",
                    value: "B2"
                },
                {
                    text: "C3路侧停车点",
                    value: "C3"
                }
            ],
            berthOptions: []
        };
    },
    computed: {
        // 表单是否有效
        isFormValid() {
            return (
                this.selectedParking &&
                this.selectedBerth &&
                (this.licensePlate || this.vimCode) &&
                this.year &&
                this.month &&
                this.day &&
                this.hour &&
                this.minute &&
                this.second
            );
        },

        yearOptions() {
            return this.generateOptions(2020, 2030);
        },
        monthOptions() {
            return this.generateOptions(1, 12, true);
        },
        dayOptions() {
            return this.generateOptions(1, 31, true);
        },
        hourOptions() {
            return this.generateOptions(0, 23, true);
        },
        minuteOptions() {
            return this.generateOptions(0, 59, true);
        },
        secondOptions() {
            return this.generateOptions(0, 59, true);
        }
    },
    mounted() {
        // // 设置默认的停车点和泊位点
        // if (this.parkData1.parking_spot) {
        //     this.selectedParkingText = this.parkData1.parking_spot;
        //     // 找到对应的停车点值
        //     // const parkingItem = this.parkingOptions.find(item => item.text === this.parkData1.parking_spot);
        //     // if (parkingItem) {
        //     //     this.selectedParking = parkingItem.value;
        //     // }
        // }
        // if (this.parkData1.berth) {
        //     this.selectedBerthText = this.parkData1.berth;
        //     // 找到对应的泊位点值
        //     // const berthItem = this.berthOptions.find(item => item.text === this.parkData1.berth);
        //     // if (berthItem) {
        //     //     this.selectedBerth = berthItem.value;
        //     // }
        // }
        this.getParkingList();
        this.getParkingBerthList();
    },
	
	 watch: {
	    // 监听 parkData1 的变化
	    parkData1: {
	      immediate: true, // 立即触发一次
	      handler(newVal) {
	        if (newVal.parking_spot) {
	          this.selectedParkingText = newVal.parking_spot;
	        }
	        if (newVal.berth) {
	          this.selectedBerthText = newVal.berth;
	        }
	      }
	    }
	  },
    methods: {
        // 获取停车场列表
        async getParkingList() {
            try {
                const response = await this.baseService.get(
                    "/parking/bizParkingLots/queryList?parkingType=20"
                );
                if (response.code == 200) {
                    this.parkingOptions = response.result.map(parking => ({
                        text: parking.parkingName,
                        value: parking.id
                    }));
                    if (this.parkData && this.parkData.code) {
                        // 复显停车点位
                        let parkId = this.parkingOptions.find(item => {
                            return item.value == this.parkData.parkId;
                        });
                        this.selectedParkingText = parkId.text;
                        this.selectedParking = parkId.value;
                    }
                } else {
                    this.$toast("获取停车场列表失败");
                }
            } catch (error) {
                console.error("获取停车场列表失败: ", error);
                this.$toast("获取停车场列表失败");
            }
        },
        // 查询泊位列表
        async getParkingBerthList() {
            try {
                const response = await this.baseService.get(
                    "/parking/parkingCarPort/list"
                );
                if (response.code == 200) {
                    this.berthOptions = response.result.map(berth => ({
                        text: berth.name,
                        value: berth.parkingId
                    }));
                    if (this.parkData && this.parkData.code) {
                        // 复现泊位号
                        let parkNo = this.berthOptions.find(item => {
                            return item.value == this.parkData.parkingId;
                        });
                        this.selectedBerthText = parkNo.text;
                        this.selectedBerth = parkNo.value;
                    }
                }
            } catch (error) {
                console.error("获取泊位列表失败: ", error);
                this.$toast("获取泊位列表失败");
            }
        },

    // formatterUpperCase(value) {
    //   return value.replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
    // },
    generateOptions(start, end, pad = false) {
      return Array.from(
        {
          length: end - start + 1
        },
        (_, i) => {
          const value = i + start;
          return {
            text: pad ? value.toString().padStart(2, "0") : value.toString(),
            value: value
          };
        }
      );
    },
    onParkingConfirm(value) {
      this.selectedParking = value.value;
      this.selectedParkingText = value.text;
      this.showParkingPicker = false;
    },
    // 泊位选择点击事件
    onBerthClick() {
      if (!this.selectedParking) {
        this.$toast("请先选择停车点");
      } else {
        this.showBerthPicker = true;
      }
    },
    // 泊位选择确认
    onBerthConfirm(value) {
      this.selectedBerth = value.value;
      this.selectedBerthText = value.text;
      this.showBerthPicker = false;
    },
    onYearConfirm(value) {
      this.year = value.value;
      this.showYearPicker = false;
    },
    onMonthConfirm(value) {
      this.month = value.value;
      this.showMonthPicker = false;
    },
    onDayConfirm(value) {
      this.day = value.value;
      this.showDayPicker = false;
    },
    onHourConfirm(value) {
      this.hour = value.value;
      this.showHourPicker = false;
    },
    onMinuteConfirm(value) {
      this.minute = value.value;
      this.showMinutePicker = false;
    },
    onSecondConfirm(value) {
      this.second = value.value;
      this.showSecondPicker = false;
    },
    // 创建订单
    createOrder() {
      if (this.isFormValid) {
        // 这里可以添加创建订单的逻辑
        let data = {
          showParkingPicker: this.selectedParkingText, // 停车点位选择器是否显示
          carportCode: this.selectedBerthText,
          carNumber: this.licensePlate,
          carportDeviceCode: "",
          vimCode: this.vimCode,
          parkingId: this.selectedParking,
          berthId: this.selectedBerth,
          startTime:
            this.year +
            "-" +
            this.month +
            "-" +
            this.day +
            " " +
            this.hour +
            ":" +
            this.minute +
            ":" +
            this.second
        };
        this.baseService
          .post(
            "/parking/bizParkingOrder/createParkingOrder",
            data
          )
          .then(res => {
            if (res.code == 200) {
              this.$toast(res.message);
              this.$router.push({
                path: "/xcHome"
              });
            } else {
              this.$toast.warning(res.message);
            }
          });
      } else {
        this.$toast("请填写完整信息");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.orderInfo {
    font-size: 16px;
    width: 100%;
    height: 86%;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    overflow: auto;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .back-btn {
            border: 0px solid #fff;
            padding: 0 15px;

            .list-icon {
                color: #333;
                font-size: 20px;
                font-weight: bold;
            }
        }
    }

    .form-container {
        background-color: rgb(219, 234, 254);
        padding: 15px;
        border-radius: 8px;
        height: 93%;
        display: flex;
        flex-direction: column;
        justify-content: space-between; // 让内容在容器内均匀分布

        .form-item {
            margin-bottom: 15px;

            label {
                display: block;
                margin-bottom: 8px;
                font-size: 15px;
                color: #666;
                font-weight: 600;
            }

            .time-picker {
                display: flex;
                gap: 10px;
                margin-bottom: 5px;

                .van-select {
                    flex: 1;
                }
            }

            .van-cell {
                width: 65%;
                padding: 4px 6px;
                height: 30px;
                border-radius: 10px;
            }
        }

        // 创建订单按钮的样式调整
        .form-item:last-child {
            display: flex;
            justify-content: center; // 水平居中
            align-items: center; // 垂直居中
            margin-top: auto; // 将按钮推到容器底部
            margin-bottom: 0; // 移除底部间距

            .van-button {
                width: 120px;
                border-radius: 10px;
            }
        }
    }
}
</style>
<style lang="less" scoped